/** 迭代中间件列表, 进行组合
 *
 * @param middlewareList 中间件列表
 * @param options 用于中间件之间传递的参数
 * @returns 返回组合后的请求回调
 */
function setMiddleware(middlewareList, options) {
    let onRequest = () => { };
    function setMiddle(next) {
        const current = middlewareList.pop();
        if (current) {
            const newNext = () => {
                current(options, next);
            };
            if (middlewareList.length) {
                setMiddle(newNext);
            }
            else {
                onRequest = newNext;
            }
        }
    }
    setMiddle(() => { }); // 设置中间件
    return onRequest;
}
/** 合并中间件
 *
 * @param middlewareList 中间件列表, 通过 app.use 插入
 * @param extraOptions 中间件之间传输的额外参数对象
 * @returns 返回一个用于 on("request") 的监听回调
 */
export function combineMiddleware(middlewareList, extraOptions) {
    return (request, response) => {
        if (middlewareList.length) {
            const options = { request, response, ...extraOptions };
            const onRequest = setMiddleware([...middlewareList], options);
            onRequest(options, () => { });
        }
    };
}
